package com.goodjia.phase1module4;

public class TrainTicketRunnableTest implements Runnable{

    private int ticketCount;// 用于描述火车票剩余票数
    private static LockFlag lockFlag = new LockFlag();// 同步锁需要的一个类对象

    public TrainTicketRunnableTest() {
    }

    public TrainTicketRunnableTest(int ticketCount) {
        this.ticketCount = ticketCount;
    }

    public int getTicketCount() {
        return ticketCount;
    }

    public void setTicketCount(int ticketCount) {
        this.ticketCount = ticketCount;
    }

    @Override
    public void run() {
        System.out.println("线程" + Thread.currentThread().getName() + "已启动");
        synchronized (lockFlag) {
            int temp = getTicketCount();
            if (temp > 0) {
                temp -= 1;
                System.out.println("正在出票...请稍后");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("出票成功!");
                System.out.println("请取走您的票");
            } else {
                System.out.println("余票不足请等待");
            }
            setTicketCount(temp);// 重新设置余票数量
            System.out.println("剩余票数为：" + getTicketCount());
            System.out.println("--------------------");
        }
    }

    public static void main(String[] args) {

        TrainTicketRunnableTest ttrt = new TrainTicketRunnableTest(100);
        // 通过实现Runnable接口的引用作为参数创建三个线程
        Thread t1 = new Thread(ttrt);
        Thread t2 = new Thread(ttrt);
        Thread t3 = new Thread(ttrt);

        // 启动三个线程
        t1.start();
        t2.start();
        t3.start();

        // 主线程等待三个线程执行完
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("剩余票数为：" + ttrt.getTicketCount());

    }
}
